budgetEnforcementTotal = 1;

$(function() {
	localStorage.setItem('url',
		localStorage.getItem('url') ? localStorage.getItem('url') :
		`getdata?username=${getUsername}&budgetYear=${fullYear}&budgetMonth=${fullMonth}&dept=${fullDepartment}&status=2&chartPage=7040401&chartNo=1&budgetNo=0001`
	)
	let lisData;
	initBudgetEnforcementTotal()
})
const weidu = '预算树状图';

function initBudgetEnforcementTotal() {
	getAllData()
}

function getAllData() {
	// 直接成本 领域维度 存储预算号
	localStorage.setItem('budgetNo', localStorage.getItem('url').split('&').find(item => item.indexOf('budgetNo') > -1)
		.split('=')[1])
	$('.vessel .main .tabs') && $('.vessel .main .tabs').remove()
	$.get(`${API_URL}${newUrl(localStorage.getItem('url'))}`, {}, function(res) {
		const resp = eval("(" + res + ")").items[0].charts[0];
		$('.vessel .aside').html('')
		$('header .tabbar').html('')
		if (resp.data.length > 0) {
			$('.vessel .main').html(`<ul></ul>
							<div class="item-detail box">
								<div class="month">
									<div class="headline">
										<h3>月度预算执行情况</h3>
									</div>
									<div id="monthlj"></div>
								</div>
								<div class="state">
									<div class="">
										<h4>执行率说明</h4>
										<div class="edit">
											<img src="assets/images/capital/edit.svg">
											<div class="mask-position">
												<div class="mask-content">
													<div class="mask-write-area">
														<textarea placeholder="请输入"></textarea>
													</div>
													<div class="btn">
														<button class="cancle">取消</button>
														<button class="save">保存</button>
													</div>
												</div>
											</div>
										</div>
									</div>
									<div class="p"></div>
								</div>
							</div>`)
			renderAsideFigure(newUrl(resp.data[0].key20))
			renderAsideTree(newUrl(resp.data[0].key19))
			renderMenu(newUrl(resp.data[0].key25))
			isMulti(newUrl(resp.data[0].key14), function() {
				console.log(localStorage.getItem('isMulti'))
				console.log(localStorage.getItem('multiLiType'))
				if (localStorage.getItem('isMulti') !== 'true' || localStorage.getItem(
						'multiLiType') === weidu) {
					renderMainLi(resp.data)
				} else {
					getMultiData()
				}
			})
			// 直接成本
			if (localStorage.getItem('budgetNo') === '00010001') {
				rendercllyTabs()
			}
		} else {
			$('.vessel .main').html(`<div class="nowrap" style="width:calc(100% - 32px);margin:16px;border-radius:16px;">
									<div class="noData">
										<img src="assets/images/mask/budget-All-IncomingPayment.svg" >
										<p>当前条件下没有可查看的预算执行数据</p>
									</div>
								</div>`)
		}
	})
}

function isMulti(url, callBack) {
	$.get(`${API_URL}${url}`, {}, function(res) {
		const data = eval("(" + res + ")").items[0].charts[0].data;
		if (data.length > 0) {
			localStorage.setItem('isMulti', 'true')
		} else {
			localStorage.setItem('isMulti', 'false')
		}
		callBack && callBack()
	})
}

function newUrl(url) {
	if (url && url.indexOf("&") !== -1) {
		return url.split('&').map(item => {
			if (item.indexOf('budgetYear') !== -1) {
				return `budgetYear=${fullYear}`
			} else if (item.indexOf('budgetMonth') !== -1) {
				return `budgetMonth=${fullMonth}`
			} else if (item.indexOf('dept') !== -1) {
				return `dept=${fullDepartment}`
			} else if (item.indexOf('#执行率说明#') !== -1) {
				return item.replace('#执行率说明#', $('.vessel .main .item-detail .state div .mask-content textarea')
					.val())
			}
			return item
		}).join('&')
	} else {
		return url
	}

}

function renderAsideTree(url) {
	$.get(`${API_URL}${url}`, {}, function(res) {
		const data = eval("(" + res + ")").items[0].charts[0].data;
		$('.vessel .aside .title') && $('.vessel .aside .title').remove()
		if (data.length > 1) {
			const trees = data.map((item, i) => {
				if (i === data.length - 1) {
					return `<h4>${item.key02}</h4>`
				} else {
					return `<span data-url="${item.key03}">${item.key02}/</span>`
				}
			}).join('')
			const treeHtml = `<div class="title">${trees}</div>`
			$('.vessel .aside').prepend(treeHtml)
		}
	})
}

function renderAsideFigure(url) {
	$.get(`${API_URL}${url}`, {}, function(res) {
		const resp = eval("(" + res + ")").items[0].charts[0];
		const name = chart_name(resp.chart_name);
		const data = resp.data[0];
		$('.vessel .aside .budget') && $('.vessel .aside .budget').remove()
		$('.vessel .aside .statistics') && $('.vessel .aside .statistics').remove()
		const figure = name.map((item, i) => {
			const key = `key0${i+1}`
			if (i === 0) {
				return `<div class="budget">
												<h3>${item}</h3>
												<h2>${(data[key])}<span>万元</span></h2>
								</div>`
			} else if (i === name.length - 1) {
				return `<div class="statistics">
													<h4>执行率</h4>
													<h3>${data[key]}%</h3>
													<div class="progress-bar">
														<div style="max-width: 100%;width:${data[key]}%" class="progress ${data[key]>100?'over':''}"></div>
													</div>
												</div>`
			} else {
				return `<div class="statistics">
											<h4>${item}</h4>
											<h3>${(data[key])}<span>万元</span></h3>
										</div>`
			}
		}).join('')
		$('.vessel .aside').append(figure)
	})
}

function renderMenu(url) {
	console.log(url)
	localStorage.getItem('multiLiType') && localStorage.removeItem('multiLiType')
	$.get(`${API_URL}${url}`, {}, function(res) {
		const data = eval("(" + res + ")").items[0].charts[0].data;
		if (data.length > 0) {
			const menus = data.map(item => {
				return `<p class="${item.key04==='1'?'active':''}">${item.key02}</p>`
			}).map((it, index) => (
				$(it).on('click', function() {
					if ($(this).text() !== $('.vessel .aside .title h4').text()) {
						$(this).siblings().removeClass('active');
						$(this).addClass('active')
						data[index].key03 && localStorage.setItem('url', data[index].key03)
						data[index].key05 && localStorage.setItem('multiUrl', data[index].key05)
						getAllData()
					}
				})
			))
			$('header .tabbar').html(menus)
		}
	})
}

function renderMainLi(data) {
	lisData = data;
	const lis = data.map((item, i) => {
		let li = `<li class="${i===0?'active':''}" data-index="${i}">
						<div class="title">
							<h3>${item.key03}</h3>`
		li += (item.key15 === '1' || item.key16 === '1') ? `<a data-index="${i}" data-type="${item.key15==='1'&&item.key16==='0'?item.key03:''}">
								<img src="assets/images/departmental-charge/right.svg">
							</a>` : ''
		li += `</div>
						<div class="rate">
							<div class="chart">
								<svg><circle cx="35" cy="35" r="32" stroke="#E2E2EA"  stroke-width="2" fill="rgba(255, 255, 255, 0.2)" stroke-linecap="round" /><circle cx="35" cy="35" r="32" stroke="${item.key10>100?'#F53F3F':'#0062FF'}" stroke-width="5" fill="none" stroke-dasharray="${Math.PI * 64}" stroke-dashoffset="${Math.PI * 64 * ((100 - item.key10)<0?0:(100 - item.key10)/100)}" stroke-linecap="round" /></svg><span>${item.key10}%</span></div><p>执行率</p>
						</div>
						<div class="statistics">
							<h4>预算金额</h4>
							<h3>${item.key04}<span>万元</span></h3>
						</div>
						<div class="statistics">
							<h4>执行金额</h4>
							<h3>${item.key06}<span>万元</span></h3>
						</div>
						<div class="statistics">
							<h4>剩余金额</h4>
							<h3>${item.key05}<span>万元</span></h3>
						</div>
						<button>查看明细</button>
					</li>`
		return li
	}).join('')
	$('.vessel .main ul').html(lis)
	renderMainChart(newUrl(data[0].key13))
	getratestate(newUrl(data[0].key23), 0)
}

// 直接成本领域维度
function renderlywdLi(data) {
	const lis = data.map((item, i) => {
		let li = `<li class="${i===0?'active':''}" data-index="${i}">
						<div class="title">
							<h3>${item.key03}</h3>`
		li += item.budget_no ? `<a data-budgetname="${item.key03}" data-budgetno="${item.budget_no}">
								<img src="assets/images/departmental-charge/right.svg">
							</a>` : ''
		li += `</div>
						<div class="rate">
							<div class="chart">
								<svg><circle cx="35" cy="35" r="32" stroke="#E2E2EA"  stroke-width="2" fill="rgba(255, 255, 255, 0.2)" stroke-linecap="round" /><circle cx="35" cy="35" r="32" stroke="${item.key06>100?'#F53F3F':'#0062FF'}" stroke-width="5" fill="none" stroke-dasharray="${Math.PI * 64}" stroke-dashoffset="${Math.PI * 64 * ((100 - item.key06)<0?0:(100 - item.key06)/100)}" stroke-linecap="round" /></svg><span>${item.key06}%</span></div><p>执行率</p>
						</div>
						<div class="statistics">
							<h4>预算金额</h4>
							<h3>${item.key04}<span>万元</span></h3>
						</div>
						<div class="statistics">
							<h4>执行金额</h4>
							<h3>${item.key05}<span>万元</span></h3>
						</div>
						<div class="statistics">
							<h4>剩余金额</h4>
							<h3>${item.key07}<span>万元</span></h3>
						</div>
						<button>查看明细</button>
					</li>`
		return li
	}).join('')
	$('.vessel .main ul').html(lis)
}

function renderMultiMainLi(data) {
	lisData = data;
	const lis = data.map((item, i) => {
		let li = `<li class="${i===0?'active':''}" data-index="${i}">
						<div class="title">
							<h3>${item.key01}</h3><a data-type='${item.key01}' data-index="${i}">
								<img src="assets/images/departmental-charge/right.svg">
							</a></div>
						<div class="statistics">
							<h4>执行金额</h4>
							<h3>${item.key03}<span>万元</span></h3>
						</div>
					</li>`
		return li
	}).join('')
	$('.vessel .main ul').html(lis)
	renderMainChart(newUrl(data[0].key04))
	getratestate(newUrl(data[0].key07), 0)
}

function renderMainChart(url) {
	$.get(`${API_URL}${url}`, {}, function(res) {
		const resp = eval("(" + res + ")").items[0].charts[0];
		const name = chart_name(resp.chart_name, ' ').splice(2);
		const data = resp.data;
		if (data.length === 0) {
			if (document.querySelector('#monthlj')) {
				document.querySelector('#monthlj') && document.querySelector('#monthlj').remove()
				document.querySelector('.month').innerHTML += `<div class="nowrap">
									<div class="noData">
										<img src="assets/images/mask/budget-All-IncomingPayment.svg" >
										<p>暂无数据</p>
									</div>
								</div>`
			}
			return
		}
		if (document.querySelector('.nowrap')) {
			document.querySelector('.nowrap').remove();
			document.querySelector('.month').innerHTML += `<div id="monthlj"></div>`
		}
		const legendData = name;
		const colors = ['#165DFF', '#50CD89', '#7239EA']
		let xData = [];
		for (let i = 0; i < data.length; i++) {
			xData.push(+data[i].key01);
		}
		const Data = [];
		for (let i = 0; i < legendData.length; i++) {
			Data.push({
				name: legendData[i],
				type: legendData[i].indexOf('率') > -1 ? "line" : "bar",
				barWidth: '30%',
				barGap: 0,
				yAxisIndex: legendData[i].indexOf('率') > -1 ? 1 : 0,
				itemStyle: {
					color: legendData.length > 1 ? colors[i] : colors[1],
				},
				data: [],
			})
			for (const item of data) {
				Data[i].data.push(item['key0' + (i + 2)])
			}
		}
		have("monthlj") ? mulitYBar("monthlj", xData, legendData, Data, '月', true, (legendData
			.length > 1)) : "";
	})

}

let ratestateIndex = 0;

function getratestate(url, index) {
	$.get(`${API_URL}${url}`, {}, function(res) {
		const val = eval("(" + res + ")").items[0].charts[0].data.length > 0 ? eval("(" + res + ")").items[0]
			.charts[0].data[0].key01 : '';
		$('.vessel .main .item-detail .state .p').html(val);
		ratestateIndex = index;
	})
}

$('.vessel .main').on('click', 'ul li', function() {
	$(this).siblings().removeClass('active')
	$(this).addClass('active')
	const index = $(this)[0].dataset.index;
	if (localStorage.getItem('isMulti') === 'true' && localStorage.getItem('multiLiType') !== weidu) {
		renderMainChart(newUrl(lisData[index].key04))
		getratestate(newUrl(lisData[index].key07), index)
	} else {
		renderMainChart(newUrl(lisData[index].key13))
		getratestate(newUrl(lisData[index].key23), index)
	}
})
// 直接成本 领域维度
$('.vessel .main').on('click', 'ul li a', function(e) {
	e.stopPropagation()
	if ($(this)[0].dataset.budgetname && $(this)[0].dataset.budgetno) {
		const url = `getdata?current_username=${getUsername}&current_year=${fullYear}&current_month=${fullMonth}&current_dept=${fullDepartment}&budget_name=${$(this)[0].dataset.budgetname}&budget_no=${$(this)[0].dataset.budgetno}&parent_budget_no=`
		renderlywdsecond(url)
	} else {
		if (!$(this)[0].dataset.type) {
			localStorage.setItem('isMulti', lisData[$(this)[0].dataset.index].key22 ? true : false)
			const newUrl = lisData[$(this)[0].dataset.index].key18
			localStorage.setItem('url', newUrl)
			localStorage.getItem('isMulti') === 'true' && localStorage.setItem('multiUrl', lisData[$(this)[0]
				.dataset.index].key22)
			getAllData()
			if (localStorage.getItem('isMulti') === 'true') {
				getMultiData()
			}
		} else {
			const tabIndex = [].slice.call($('.vessel .main .tabs p')).findIndex(item => {
				return $(item).hasClass('active') === true
			})
			const islingyu = localStorage.getItem('multiLiType') === weidu || localStorage.getItem(
				'isMulti') ===
				'false';
			localStorage.setItem('treeAsideTree', !islingyu ? lisData[$(this)[0].dataset.index].key09 : lisData[
				$(
					this)[0].dataset.index].key26)
			localStorage.setItem("treeTotal", !islingyu ? lisData[$(this)[0].dataset.index].key06 : lisData[$(
				this)[
				0].dataset.index].key17)
			localStorage.setItem("treeCourse", !islingyu ? lisData[$(this)[0].dataset.index].key05 : lisData[$(
				this)[0].dataset.index].key14)
			window.location.href =
				`budget-enforcement-total-tree.html?index=${tabIndex}&type=${$(this)[0].dataset.type}`;
		}
	}
})
// 直接成本 领域维度下一级页面
function renderlywdsecond(url){
	localStorage.setItem('url', newUrl)
	// $.get(`${API_URL}${url}`, {}, function(res) {
	// 	const resp = eval("(" + res + ")").items[0].charts[0];
	// })
	$('.vessel .main .tabs') && $('.vessel .main .tabs').remove()
	renderlywdLi([{
			'key03': '材料',
			'key04': '1110',
			'key05': '1000',
			'key06': '80',
			'key07': '1110'
		},
		{
			'key03': '织物',
			'key04': '1110',
			'key05': '1000',
			'key06': '80',
			'key07': '1110'
		}, {
			'key03': '工序试验、专用设备、转拨款',
			'key04': '1110',
			'key05': '1000',
			'key06': '80',
			'key07': '1110'
		}, {
			'key03': '工装',
			'key04': '1110',
			'key05': '1000',
			'key06': '80',
			'key07': '1110'
		}, {
			'key03': '事务费',
			'key04': '1110',
			'key05': '1000',
			'key06': '80',
			'key07': '1110'
		}
	])
}
// 直接成本 领域维度
function rendercllyTabs() {
	const tabs =
		`<p data-url=${localStorage.getItem('url')}>成本类别</p><p data-url='getdata?current_username=${getUsername}&current_year=${fullYear}&current_month=${fullMonth}&current_dept=${fullDepartment}'>领域维度</p>`
	$('.vessel .main').prepend(`<div class="tabs">${tabs}</div>`)
	document.querySelectorAll('.main .tabs p')[0].classList.add('active')
	for (const [index, tab] of document.querySelectorAll('.vessel .main .tabs p').entries()) {
		tab.addEventListener('click', function() {
			const activeTab = document.querySelector('.vessel .main .tabs p.active');
			activeTab && activeTab.classList.remove('active')
			this.classList.add('active')
			if ($(this)[0].innerText === '领域维度') {
				// $.get(`${API_URL}${$(this)[0].dataset.url}`, {}, function(res) {
				// 	const resp = eval("(" + res + ")").items[0].charts[0];
				// })
				renderlywdLi([{
						'key03': '纵向',
						'key04': '1110',
						'key05': '1000',
						'key06': '80',
						'key07': '1110',
						'budget_no': '0001000100030001'
					},
					{
						'key03': '预研',
						'key04': '1110',
						'key05': '1000',
						'key06': '80',
						'key07': '1110',
						'budget_no': '0001000100030003'
					}, {
						'key03': '工艺',
						'key04': '1110',
						'key05': '1000',
						'key06': '80',
						'key07': '1110',
						'budget_no': '0001000100030002'
					}, {
						'key03': '横向',
						'key04': '1110',
						'key05': '1000',
						'key06': '80',
						'key07': '1110',
						'budget_no': '0001000100030004'
					}, {
						'key03': '民品',
						'key04': '1110',
						'key05': '1000',
						'key06': '80',
						'key07': '1110',
						'budget_no': '0001000100030005'
					}
				])
			} else {
				localStorage.setItem('url', $(this)[0].dataset.url)
				getAllData()
			}
		})
	}
}
$('.vessel .main').on('click', 'ul li button', function(event) {
	event.stopPropagation()
	$('.mask').show()
	getTableData()
})
$('.mask .mask-content .title img').click(function() {
	$('.mask').hide()
})

function getMultiData() {

	$.get(`${API_URL}${newUrl(localStorage.getItem('multiUrl'))}`, {}, function(res) {
		const data = eval("(" + res + ")").items[0].charts[0].data;
		renderTabs(data)
	})

}

function renderTabs(data) {
	$('.vessel .main .tabs') && $('.vessel .main .tabs').remove()
	const tabs = data.map(item =>
		`<p data-cource="${item.key03}" data-type="${item.key02}">${item.key01}</p>`).join(
		'')
	$('.vessel .main').prepend(`<div class="tabs">${tabs}</div>`)
	document.querySelectorAll('.main .tabs p')[0].classList.add('active')
	getMultiLiData(newUrl(data[0].key03), data[0].key02)
	for (const [index, tab] of document.querySelectorAll('.vessel .main .tabs p').entries()) {
		tab.addEventListener('click', function() {
			const activeTab = document.querySelector('.vessel .main .tabs p.active');
			activeTab && activeTab.classList.remove('active')
			this.classList.add('active')
			tabIndex = index;
			getMultiLiData(newUrl(data[index].key03), data[index].key02)
		})
	}
}



function getMultiLiData(url, type) {
	localStorage.setItem('multiLiType', type)
	$.get(`${API_URL}${url}`, {}, function(res) {
		const resp = eval("(" + res + ")").items[0].charts[0];
		if (type === weidu) {
			renderMainLi(resp.data)
		} else {
			renderMultiMainLi(resp.data)
		}
	})
}
$('.vessel .main').on('click', '.edit .mask-content .btn button.save', function() {
	const url = localStorage.getItem('isMulti') === 'true' && localStorage.getItem('multiLiType') !== weidu ?
		newUrl(lisData[ratestateIndex].key08) : newUrl(lisData[ratestateIndex].key24)
	$.get(`${API_URL}${url}`, {}, function(res) {
		let re = eval("(" + res + ")");
		alert(re.items[0].charts[0].chart_name)
		getratestate(localStorage.getItem('isMulti') === 'true' && localStorage.getItem(
			'multiLiType') !== weidu ? newUrl(lisData[ratestateIndex].key07) : newUrl(lisData[
			ratestateIndex].key23), ratestateIndex)
		toggle()
	})
})
$('.vessel .main').on('click', '.item-detail .state div img', function() {
	document.querySelector(
			'.vessel .main .item-detail .state div .mask-content textarea').value = document
		.querySelector('.vessel .main .item-detail .state .p').innerText
	toggle()
})


$('.vessel .aside').on('click', '.title span', function() {
	removeStorage()
	localStorage.setItem('url', $(this)[0].dataset.url)
	getAllData()
})

function removeStorage() {
	localStorage.removeItem('multiUrl')
	localStorage.removeItem('multiLiType')
	localStorage.removeItem('isMulti')
	localStorage.removeItem('url')
}
$('.vessel .main').on('click', '.edit .mask-content .btn button.cancle', function() {
	toggle()
})


function toggle() {
	document.querySelector('.edit .mask-position').style.display = document.querySelector(
		'.edit .mask-position').style.display !== 'block' ? 'block' : 'none'
}

function chart_name(name, str = '；') {
	const legend = name.split(str);
	return legend.map(item => {
		let newIt = item.split('-').splice(1)[0]
		if (newIt.indexOf('{') > -1) {
			newIt = newIt.replace('{', '')
		}
		if (newIt.indexOf('}') > -1) {
			newIt = newIt.replace('}', '')
		}
		return newIt
	})
}


function renderTable1(data) {
	const columns = [
		[{
				field: 'key01',
				title: '预算项目编号',
				align: 'left',
				formatter: blodText
			}, {
				field: 'key03',
				title: '预算科目',
				align: 'right',
				formatter: blodText
			},
			{
				field: 'key04',
				title: '预算数',
				align: 'right',
				formatter: wyText
			},
			{
				field: 'key05',
				title: '完成数(已执行)',
				align: 'right',
				formatter: wyText
			},
			{
				field: 'key06',
				title: '完成数(占用)',
				align: 'right',
				formatter: wyText
			},
			{
				field: 'key07',
				title: '完成数',
				align: 'right',
				formatter: wyText
			},
			{
				field: 'key08',
				title: '差额',
				align: 'right',
				formatter: wyText
			}
		]
	]
	renderTable('table1', data, columns, false)
}

function renderTable(elId, data, columns, isShowFooter) {
	let $table = $(`#${elId}`);
	$table.bootstrapTable('destroy');
	$table.bootstrapTable({
		data: data,
		height: $(`.${elId}`).height(),
		idField: 'id',
		showColumns: false,
		fixedColumns: true,
		fixedNumber: 1,
		fixedRightNumber: 1,
		showFooter: isShowFooter,
		columns: columns,
		treeShowField: 'key01',
		parentIdField: 'pid',
		onPostBody: function() {
			var columns = $table.bootstrapTable('getOptions').columns
			if (columns && columns[0][1].visible) {
				$table.treegrid({
					treeColumn: 0,
					onChange: function() {
						$table.bootstrapTable('resetView')
					}
				})
			}
		}
	})
}


function total() {
	return '总计'
}

function wyText(value) {
	return `<p>${value}</p>`
}

function blodText(value) {
	return `<h6>${value}</h6>`
}

function getTableData() {
	const currYear = localStorage.getItem("year");
	const currMon = localStorage.getItem("month");
	$.get(
		`${API_URL}getdata?budgetYear=${currYear}&budgetMonth=${currMon}&status=2&chartPage=604&chartNo=4&username=${getUsername}`, {},
		function(res) {
			console.log(res)
			let re = eval("(" + res + ")");
			console.log(re)
			let data = re.items[0].charts[0].data;
			let id = 0;
			let parentData = [];
			for (let i = 0; i < data.length; i++) {
				if (data[i].key02 == '') {
					++id;
					data[i].id = id;
					data[i].pid = 0;
					parentData.push(data[i])
				}
			}
			for (let i = 0; i < parentData.length; i++) {
				for (let j = 0; j < data.length; j++) {
					if (parentData[i].key01 == data[j].key02) {
						data[j].pid = parentData[i].id
					}
				}
			}
			renderTable1(data)
		}
	)
}